package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Override
    public List<SkuDTO> listSkuByIds(List<Long> ids) {
        return SkuDTO.convertEntityList(this.listByIds(ids));
    }

    @Override
    public List<SkuDTO> listSkuBySpu(Long spuId) {

        //select * from tb_sku where spu_id = #{spuId}

        return SkuDTO.convertEntityList(this.query().eq("spu_id",spuId).list());
    }

    @Override
    @Transactional
    public void minusStock(Map<Long, Integer> cartsMap) {
        List<Sku> skus = listByIds(cartsMap.keySet());

        skus.forEach(sku -> {
            Long skuId= sku.getId();
            Integer num = cartsMap.get(skuId);
            sku.setStock(sku.getStock()-num);
            sku.setSold(sku.getSold()+num);
        });
        this.updateBatchById(skus);
    }
}
